package com.element.security.single.handler;

import com.common.core.exception.code.SecurityErrorCode;
import com.common.core.results.VoidResult;
import com.element.security.single.utils.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginFailureHandler implements AuthenticationFailureHandler {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException {
        logger.error("AuthenticationException异常,请求路径:{},异常信息:", request.getServletPath(), e);
        VoidResult result;
        if (e instanceof AccountExpiredException) {
            result = VoidResult.failed(SecurityErrorCode.A_ACCOUNT_EXPIRED_EXCEPTION);
        } else if (e instanceof BadCredentialsException) {
            result = VoidResult.failed(SecurityErrorCode.A_USERNAME_OR_PASSWORD_ERROR);
        } else if (e instanceof CredentialsExpiredException) {
            result = VoidResult.failed(SecurityErrorCode.A_CREDENTIALS_EXPIRED_EXCEPTION);
        } else if (e instanceof DisabledException) {
            result = VoidResult.failed(SecurityErrorCode.A_DISABLED_EXCEPTION);
        } else if (e instanceof LockedException) {
            result = VoidResult.failed(SecurityErrorCode.A_LOCKED_EXCEPTION);
        } else if (e instanceof InternalAuthenticationServiceException) {
            result = VoidResult.failed(SecurityErrorCode.A_INTERNAL_AUTHENTICATION_SERVICE_EXCEPTION);
        } else if (e instanceof UsernameNotFoundException) {
            result = VoidResult.failed(SecurityErrorCode.A_USERNAME_OR_PASSWORD_ERROR);
        } else {
            result = VoidResult.failed(SecurityErrorCode.SYS_EXCEPTION_CODE);
            result.setErrMsg("认证异常");
        }
        ResponseUtil.writeJson(response, result);
    }
}